const http = require('http');
const urlModule = require('url');
const fs = require('fs');
const path = require('path')

const server = http.createServer()

server.on('request', (req, res) => {
    //获取静态资源路径
    //解析前端发送的request中，用户传过来的url 路由
    let url = urlModule.parse(req.url).pathname
    if(url === '/'){
        // 调取静态首页资源
        //拿取资源的时候一定要是绝对路径
        //动态的配置绝对路径 path模版做 //dirname获取当下的路径
           fs.readFile(path.join(__dirname,'static/index.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                // 读取静态资源文件响应给游览器
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url === '/product.html'){
        fs.readFile(path.join(__dirname,'static/product.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
        }else if(url === '/images/pro-1.jpg'){
        fs.readFile(path.join(__dirname,'static/images/pro-1.jpg'),(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                res.setHeader('Content-type','image/jpeg')
                res.end(data)
            }
        })       
    }else if(url === '/images/pro-2.jpg'){
        fs.readFile(path.join(__dirname,'static/images/pro-2.jpg'),(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                res.setHeader('Content-type','image/jpeg')
                res.end(data)
            }
        })
     }else if(url === '/css/main.css'){
        fs.readFile(path.join(__dirname,'static/css/main.css'),'utf-8',(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                res.setHeader('Content-type','text/css;charset=utf-8')
                res.end(data)
            }
        })       
    }      

        // 调取静态404资源
          fs.readFile(path.join(__dirname,'static/404.html'),'utf-8',(err,data)=>{
            if(err){
                console.log(err); 
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    })

server.listen(3000, () => {
        console.log('listen port 3000...')
})
